import * as React from 'react';
import { cloneElement, useMemo } from 'react';
import { useMediaQuery } from '@material-ui/core';
import IconEvent from '@material-ui/icons/Event';
import {
    Edit,
    SimpleForm,
    SimpleList,
    List,
    Datagrid,
    NumberField,
    TextField,
    SelectField,
    DateField,
    DateInput,
    DateTimeInput,
    TextInput,
    NumberInput,
    ShowButton,
    EditButton,
    ListButton,
    SimpleShowLayout,
    Create,
    Show,
    TopToolbar,
    sanitizeListRestProps,
    useListContext,
    Filter,
    CreateButton,
    ExportButton,
    Button,
    ReferenceInput,
    ReferenceField,
    downloadCSV,
    SelectInput,
    BooleanField,
    BooleanInput,
    FunctionField
} from 'react-admin';
import { ImportButton } from "react-admin-import-csv";

import jsonExport from 'jsonexport/dist';

import { Pagination } from 'react-admin';
import ChevronLeft from '@material-ui/icons/ChevronLeft';

import QRCode from 'qrcode.react'

import {
    CustomDateTimeInput,
    CustomDateTimeField
} from './components'

const PostPagination = props => <Pagination rowsPerPageOptions={[10, 20, 50, 100]} {...props} />;

const CustomButton = <Button
    onClick={() => { alert('Your custom action'); }}
    label="Show calendar">
    <IconEvent />
</Button>


const QRCodeField = ({ source, record = {} }) => {
    return <QRCode value={record[source]} />
}

class ResourceGuesser {
    constructor(model, option = {}) {
        this.model = model
        console.log(this.model)


        this.generateInput = (option = { search: false }) => {
            return this.model.map(item => {
                let element
                if (item.field == 'id' && option.search == false) {
                    element = <TextInput key={item.field} source={item.field} disabled />
                } else if (item.readOnly == true && option.search == false) {
                    element = <TextInput key={item.field} source={item.field} disabled />
                } else if (item.type == 'string') {
                    // console.log(item)
                    if (item.referance) {
                        element = <ReferenceInput key={item.field} source={item.field} reference={item.referenceModel}>
                            <SelectInput optionText={item.referenceFiled} />
                        </ReferenceInput>
                    } else {
                        element = <TextInput key={item.field} source={item.field} required={item.required} validate={item.validate} />
                    }
                } else if (item.inputAs == 'date' || item.type == 'date') {
                    element = <DateInput key={item.field} source={item.field} />
                } else if (item.type == 'number') {
                    element = <NumberInput key={item.field} source={item.field} />
                } else if (item.type == 'boolean') {
                    element = <BooleanInput key={item.field} source={item.field} />
                } else if (item.type == 'custom') {
                    element = <TextInput key={item.field} source={item.field} required={item.required} validate={item.validate} />
                } else if (item.type == 'datetime') {
                    element = CustomDateTimeInput({ key: item.field, source: item.field })
                    // element = <CustomDateTimeInput key={item.field} source={item.field} />
                }
                return element
            })
        }
    
        this.generateField = (option = {}) => {
            return this.model.map(item => {
                let element
                if (item.choices) {
                    element = <SelectField key={item.field} source={item.field} choices={item.choices} optionText="name" optionValue="id" />
                }
                else if (item.type == 'string') {
                    if (option.list == true && item.custom == true) {
                        if (item.referance) {
                            element = <ReferenceField key={item.field} sortable={item.sortable == false ? false : true} source={item.field} reference={item.referenceModel} link="show">
                                <FunctionField source={item.referenceFiled} render={item.render} />
                            </ReferenceField >
                        } else {
                            element = <FunctionField key={item.field} source={item.field} render={item.render} />
                        }
                    } else {
                        if (item.referance) {
                            element = <ReferenceField key={item.field} sortable={item.sortable == false ? false : true} source={item.field} reference={item.referenceModel} link="show">
                                <TextField source={item.referenceFiled} />
                            </ReferenceField >
                        } else {
                            element = <TextField key={item.field} source={item.field} />
                        }
                    }
                } else if (item.type == 'date') {
                    if (option.list == true) {
                        element = <CustomDateTimeField key={item.field} source={item.field} format="yyyy-MM-DD" />
                    } else {
                        element = <CustomDateTimeField key={item.field} source={item.field} format="yyyy-MM-DD" labeld />
                    }
                } else if (item.type == 'number') {
                    element = <NumberField key={item.field} source={item.field} />
                } else if (item.type == 'boolean') {
                    element = <TextField key={item.field} source={item.field} />
                } else if (item.type == 'qrcode' && option.show == true) {
                    element = <QRCodeField key={'qrcode' + item.field} source={item.field} />
                } else if (item.type == 'datetime') {
                    // element = <DateField key={item.field} source={item.field} format={v => moment(v).utc().format("yyyy-MM-DDTHH:mm")} showTime />
                    if (option.list == true) {
                        element = <CustomDateTimeField key={item.field} source={item.field} format="yyyy-MM-DD HH:mm" />
                    } else {
                        element = <CustomDateTimeField key={item.field} source={item.field} format="yyyy-MM-DD HH:mm" labeld />
                    }
                }
                return element
            })
        }

        this.option = Object.assign({ edit: false, create: false, import: false, bulkActionButtons: false }, option)

        const EditActions = ({ basePath, data }) => (
            <TopToolbar>
                <ShowButton basePath={basePath} record={data} />
                <ListButton basePath={basePath} label="返回" icon={<ChevronLeft />} />
            </TopToolbar>
        );

        const ShowActions = ({ basePath, data }) => (
            <TopToolbar>
                {this.option.edit && <EditButton basePath={basePath} record={data} />}
                <ListButton basePath={basePath} label="返回" icon={<ChevronLeft />} />
            </TopToolbar>
        );

        this.List = props => {
            // console.log(props)
            let exporter
            if (this.option.exporter) {
                exporter = this.option.exporter
            } else {
                exporter = async (records, fetchRelatedRecords) => {
                    if (this.option.relatedRecords) {
                        for (let i = 0; i < this.option.relatedRecords.length; i++) {
                            let related = this.option.relatedRecords[i]
                            let res = await fetchRelatedRecords(records, related.source, related.table)
                            console.log(res, records[0], related.source, related.table)
                            records = records.map(record => {
                                if (record[related.source]) {
                                    return {
                                        ...record,
                                        [related.source]: res[record[related.source]][related.field]
                                    }
                                } else {
                                    return record
                                }
                            })
                        }
                    }
                    jsonExport(records, {
                    }, (err, csv) => {
                        csv = "\ufeff" + csv
                        // let url = window.URL.createObjectURL(new Blob([csv], { type: 'text/plain,charset=utf-8' }));
                        // let a = document.createElement('a')
                        // a.href = url;
                        // a.download = 'posts.csv';
                        // a.click();
                        // console.log(csv)
                        downloadCSV(csv, props.resource); // download as 'posts.csv` file
                    });
                }
            }
            const PostFilter = (props) => (
                <Filter {...props}>
                    {/* <TextInput label="Search" source="q" alwaysOn /> */}
                    {this.option.customFilter}

                    {this.generateInput({ search: true })}
                </Filter>
            );
            const ListActions = (props) => {
                const {
                    className,
                    exporter,
                    filters,
                    maxResults,
                    ...rest
                } = props;
                const {
                    currentSort,
                    resource,
                    displayedFilters,
                    filterValues,
                    hasCreate,
                    basePath,
                    selectedIds,
                    showFilter,
                    total,
                } = useListContext();

                return (
                    <TopToolbar className={className} {...sanitizeListRestProps(rest)}>
                        {filters && cloneElement(filters, {
                            resource,
                            showFilter,
                            displayedFilters,
                            filterValues,
                            context: 'button',
                        })}
                        {this.option.create && <CreateButton basePath={basePath} />}
                        {this.option.import && <ImportButton {...props} />}
                        <ExportButton
                            disabled={total === 0}
                            resource={resource}
                            sort={currentSort}
                            filterValues={filterValues}
                            maxResults={maxResults}
                        />
                        {/* Add your custom actions */}
                        { this.option.customButton && this.option.customButton}
                    </TopToolbar>
                );
            };

            return (
                <List title={this.option ? this.option.title : ''} {...props} empty={false} filters={< PostFilter />}
                    exporter={exporter}
                    pagination={< PostPagination />}
                    actions={< ListActions />} bulkActionButtons={this.option.bulkActionButtons} >
                    <Datagrid rowClick="show">
                        {this.generateField({ list: true })}
                    </Datagrid>
                </List >
            )
        }
        this.Create = props => {
            return (
                <Create {...props}>
                    <SimpleForm>
                        {this.generateInput()}
                    </SimpleForm>
                </Create>
            )
        }

        this.Edit = props => {
            return (
                <Edit {...props} actions={<EditActions />}>
                    <SimpleForm>
                        {this.generateInput()}
                    </SimpleForm>
                </Edit>
            )
        }

        this.Show = props => {
            const { hasShow, ...showProps } = props
            // console.log(props)
            return (
                <Show {...showProps} actions={<ShowActions />}>
                    <SimpleShowLayout>
                        {this.generateField({ show: true })}
                    </SimpleShowLayout>
                </Show>
            )
        }
    }

}

export {
    ResourceGuesser
}